package com.minelx.woods.task.common;

import com.alibaba.fastjson.JSON;
import com.minelx.sqlstructures.common.Files;
import com.minelx.sqlstructures.core.database.JsonDatabase;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class StructureDatabases {
	private static final Map<String, StructureDatabase> cache;

	static {
		cache = new HashMap<>();
	}

	public static StructureDatabase create(String index, String name) {
		if (cache.containsKey(identity(index, name))) {
			return cache.get(identity(index, name));
		}
		return makeCache(index, name);
	}

	private static StructureDatabase makeCache(String index, String name) {
		InputStream databaseConfig = StructureDatabases.class.getResourceAsStream("/databases/" + index + "_" + name + ".json");
		if (databaseConfig == null) {
			throw new IllegalArgumentException("database config not found, index: " + index + ", name: " + name);
		}
		// create database and save as cache
		JsonDatabase database = new JsonDatabase(JSON.parseObject(Files.toString(databaseConfig, StandardCharsets.UTF_8)));
		StructureDatabase result = new StructureDatabase(database, index, name);
		cache.put(identity(index, name), result);
		return result;
	}

	private static String identity(String index, String name) {
		return index + "@" + name;
	}
}
